import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/subject/add_frequency_type.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/util/data_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';

import 'package:hktk_app/widget/subject/preview_mask_widget.dart';

/// pdf查看
class PdfPreviewPage extends StatefulWidget {
  /// 资源文件路径
  final String url;

  /// 资源文件名称
  final String name;

  /// 资源文化类型
  final String type;

  /// 是否显示预览提示
  final bool showTips;

  /// 是否是网络文件
  final bool netWork;

  /// 栏目id
  final String columnId;

  /// 资料id
  final String resId;

  /// 是否是视频相关的资料。true：是，false：不是。默认false
  /// 控制添加观看次数方法，只有重网络查看时才添加次数，否则不添加
  final bool videoRes;

  const PdfPreviewPage({
    super.key,
    required this.url,
    required this.name,
    required this.type,
    this.showTips = false,
    this.columnId = "",
    this.netWork = true,
    this.resId = "",
    this.videoRes = false,
  });

  @override
  State<PdfPreviewPage> createState() => _PdfPreviewPageState();
}

class _PdfPreviewPageState extends State<PdfPreviewPage> {
  late BuildContext _context;

  /// 加载数据方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 文件路径
  late String _filePath;

  @override
  void initState() {
    super.initState();

    _filePath = "";
    _futureInit = _initData();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: SafeArea(child: Column(
        children: [
          PageTitleWidget(
            name: widget.name,
            pageContext: context,
            rightShow: widget.netWork,
            rightChild: downloadBtn(),
            rightFun: _onTapFunRight,
          ),
          Expanded(child: _futureItem()),
        ],
      )),
    );
  }

  /// 初始化数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.netWork) {
        File file = await DownloadDao.downloadTemporaryFile(
          url: widget.url,
          fileName: "${widget.name}.${widget.type}",
        );
        if (!widget.videoRes) {
          // 增加查看次数
          await SubjectDao.addFrequency(
            type: AddFrequencyType.watch_time,
            id: widget.resId,
          );
        } else {
          // 增加下载次数（课程）
          await CourseDao.addFrequency(
            resId: widget.resId,
          );
        }
        _filePath = file.path;
      } else {
        _filePath = widget.url;
      }

      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 异步加载组件
  _futureItem() {
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder:
          (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: context, msg: map["msg"]);
              Navigator.pop(context);

            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 内容显示方法
  _content() {
    if (_filePath != "") {
      return Stack(
        children: [
          Positioned.fill(child: _fillContent()),
          if (widget.showTips)
            Positioned.fill(
              child: PreviewMaskWidget(
                columnId: widget.columnId,
              ),
            ),
        ],
      );
    } else {
      return showNoData();
    }
  }

  /// 具体内容展示
  _fillContent() {
    return Padding(
      padding: EdgeInsets.all(20),
      child: PDFView(
        filePath: _filePath,
      ),
    );
  }

  /// 标题右边按钮组件点击方法
  _onTapFunRight() {
    if (!widget.showTips && _filePath != "") {
      // 提示，开始下载
      ToastUtil.show(context: _context, msg: "开始下载", seconds: 1);
      // 开始移动文件
      _futureDownload().then((Map<String, dynamic> map) {
        ToastUtil.show(context: _context, msg: map["msg"]);
      });
    }
  }

  /// 开始下载方法
  Future<Map<String, dynamic>> _futureDownload() async {
    Map<String, dynamic> map = {};
    try {
      if (!widget.videoRes) {
        // 增加下载次数
        await SubjectDao.addFrequency(
          type: AddFrequencyType.download_time,
          id: widget.resId,
        );
      }

      // 开始移动文件
      DataModel dataModel = dataUtilComm.dataModel;
      bool suc = await DownloadDao.fileMove(
        filePath: _filePath,
        dataModel: dataModel,
        name: widget.name,
        type: widget.type,
      );
      map["suc"] = suc;
      map["msg"] = suc ? "下载成功" : "下载失败";
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }
}
